package com.example.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

//consumer ACK机制
//  1. 设置手动签收
//  2. 让监听器类实现ChannelAwareMessageListener接口
//  3. 如果消息处理成功，则调用channel的 basicAck接口
//  4. 如果消息处理失败，则调用channel的basicNack（)，broker重新发送给consumer

@Component
public class AckListener implements ChannelAwareMessageListener {
//    @RabbitListener(queues = "confirm_queue")
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //1. 接受转换消息
            System.out.println(new String(message.getBody()));
//        2、处理业务逻辑
            System.out.println("处理业务逻辑");
//            int i =3/0;
//        3. 手动签收
            channel.basicAck(deliveryTag,true);
        } catch (Exception e) {
//            4. 拒绝签收
//            第三个参数：requeue：重回队列。如果设置为true,则消息重新回到queue 然后broker会重新发送该消息
            channel.basicNack(deliveryTag, true, true);
            e.printStackTrace();
        }
    }
}
